from  rest_framework import serializers
from .models import BackUser, UserStatusChoices, UserTypeChoices

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)           # 约束邮箱非空
    password = serializers.CharField(max_length=20, min_length=6)       # 约束密码长度


    def validate(self, attrs):              # 这里是验证逻辑，attrs是通过验证器传入的，传入的数据已经通过了验证器，这里可以进行自定义验证
        # 取出通过验证的邮箱和密码
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = BackUser.objects.filter(email=email).first()       # 获取用户
            if not user:
                raise serializers.ValidationError('请输入正确的邮箱')
            if not user.check_password(password):
                raise serializers.ValidationError('请输入正确的密码')   # 验证密码
            # 通过密码校验之后，验证用户状态是否可用
            if user.status  == UserStatusChoices.UNACTIVE:
                raise serializers.ValidationError('用户未激活')
            elif user.status == UserStatusChoices.LOCKED:
                raise serializers.ValidationError('用户被锁定')
            # 为了减少查询SQL语句的次数，将用户对象添加到attrs中
            attrs['user'] = user            # 添加用户对象到attrs中
        else:
            raise serializers.ValidationError('请输入邮箱或密码')       # 抛出验证错误
        return attrs        # 通过校验之后，返回attrs